import time

import psycopg2
import pymysql

from database.config import db_icare_pro, pymysql_icare

class GetTagMsg:

    def __init__(self,reader_no):
        self.reader_no = reader_no

    # 运营数据库
    def db_sql_operate(self,sql):
        db = psycopg2.connect(**db_icare_pro)
        cur = db.cursor()
        cur.execute(sql)
        number = cur.fetchall()

        return number

    # IOT数据库
    def db_sql_iot(self,sql):
        db = pymysql.connect(**pymysql_icare)
        cur = db.cursor()
        cur.execute(sql)
        number = cur.fetchall()

        return number

    # 在线状态
    def get_reader_binding_start(self):
        reader_status = self.db_sql_operate(f"select * from senior_product where reader_no='{self.reader_no}' and status=0")[0][-2]
        return reader_status

    # tag信息
    def new_tag_type(self):
        sing_code = self.db_sql_operate(f"select * from senior_product where reader_no='{self.reader_no}' and status=0")[0][3]
        senior_product_icare_tag = self.db_sql_operate(
            f"select * from senior_product_icare where sign_code='{sing_code}'")
        tag_list = []
        for i in senior_product_icare_tag:
            tag_list.append(i[3])
        tag_msg_lit = []
        type_tag = -1
        for tag_number in tag_list:
            if tag_number.startswith("10000"):
                type_tag = "微动感知"
            elif tag_number.startswith("105"):
                type_tag = "门磁开关"
            elif tag_number.startswith("104"):
                type_tag = "活动量"
            elif tag_number.startswith("101"):
                type_tag = "二便感知"
            elif tag_number.startswith("102"):
                type_tag = "生活感知"

            if type_tag != -1:
                tag_msg_lit.append([tag_number, type_tag])

        return tag_msg_lit

    #获取tag号
    def get_tag_msg_list(self):
        old_version_tag_no_list = []
        # ['060424', '041261']
        senior_product_list = self.db_sql_operate(f"select * from senior_product where reader_no='{self.reader_no}' and status=0")
        if len(senior_product_list) <1:
            print('该reader下没有查到tag')
            return None
        # sing_code = db_sql_operate("select * from senior_product where reader_no='6758'")
        for senior_product in senior_product_list:
            tag_no1 = senior_product[4]
            tag_no2 = senior_product[5]
            old_version_tag_no_list.append(tag_no1)
            old_version_tag_no_list.append(tag_no2)
        tag_msg_list = []
        for tag_no in old_version_tag_no_list:
            tag_type='未知'
            if tag_no!= None:
                if  tag_no.startswith('060'):
                    tag_type = "motion"
                elif tag_no.startswith('041'):
                    tag_type = "门磁开关"
                tag_msg_list.append([tag_no,tag_type])
        if len(tag_msg_list) < 1:
            tag_msg_list = self.new_tag_type()
        return tag_msg_list

    # 丢包率
    def get_tag_loss_rate(self,tag_no, start_time, end_time):
        start_time = (int)(time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S")) * 1000)
        end_time = (int)(time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S")) * 1000)
        sql = f"SELECT * FROM rssi where tag_id='{tag_no}' AND create_time> '{start_time}' AND create_time< '{end_time}' order by create_time asc"
        select_result = self.db_sql_iot(sql)
        return 'None'

    # 信号质量
    def rssi(self,tag_no):
        max_time = self.db_sql_iot(f"select MAX(create_time) from rssi where tag_id='{tag_no}'")
        time_stamp = max_time[0][0]
        rssi = self.db_sql_iot(f"select rssi from rssi where tag_id='{tag_no}'and create_time='{time_stamp}'")
        if rssi == None:
            return 'None'
        return rssi


    #获取电量
    def get_tag_battery_voltage(self):
        sum_tag_list = []
        for tag_msg in self.get_tag_msg_list():
            max_time = self.db_sql_iot(
                f"select MAX(create_time) from battery_voltage where tag_id='{tag_msg[0]}' and reader_id='{self.reader_no}'")
            time_stamp = max_time[0][0]
            if time_stamp == None:
                print(f'该tag:{tag_msg[0]}查询不到')
            else:
                tag_msg = self.db_sql_iot(f"select * from battery_voltage where tag_id='{tag_msg[0]}' and create_time='{time_stamp}' and reader_id='{self.reader_no}'")[0]
                sum_tag_list.append(tag_msg)
        return sum_tag_list


if __name__ == '__main__':
    # reader_no = '200004'
    reader_no = '64CB'
    GetTagMsg(reader_no).get_tag_msg_list()
    # a = Tag().tag_type()
    # print(a)

    #1